package com.robusta.cityuate.activities;

import java.util.Calendar;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.robusta.cityuate.R;
import com.robusta.cityuate.base.CityuateFragmentMenuActivity;
import com.robusta.cityuate.dialogs.DatePickerFragment;
import com.robusta.cityuate.dialogs.TimePickerFragment;
import com.robusta.cityuate.objects.Reservation;
import com.robusta.cityuate.objects.TimeSlot;
import com.robusta.cityuate.services.CityuateBroadCastReceiver;
import com.robusta.cityuate.services.HTTPService;
import com.robusta.cityuate.services.ReservationService;
import com.robusta.cityuate.utils.ConnectionUtils;
import com.robusta.cityuate.utils.TimeUtils;

public class ReservationActivity extends CityuateFragmentMenuActivity {

	TimeSlot timeSlot;
	private EditText startDate;
	private EditText startTime;
	private EditText endDate;
	private EditText endTime;
	private Calendar checkinDate;
	private Calendar checkoutDate;
	private Context mContext = this;
	private Button btn;

	protected static final String TAG = ReservationActivity.class.getName();
	public static final int RESERVE_CODE = 3;

	private CityuateBroadCastReceiver receiver = new CityuateBroadCastReceiver() {

		@Override
		public void onSuccess() {
			enableView();
			setSupportProgressBarIndeterminateVisibility(false);
			Toast.makeText(mContext, getString(R.string.reserved_successfuly),
					Toast.LENGTH_LONG).show();
			finish();
		}

		@Override
		public void onFailure() {
			setSupportProgressBarIndeterminateVisibility(false);
			enableView();
			// show failure message
			Toast.makeText(mContext, ConnectionUtils.getExtra(mContext, TAG),
					Toast.LENGTH_LONG).show();
			ConnectionUtils.clearConnection(mContext, TAG);

		}

		@Override
		public void onCancel() {
			enableView();
			setSupportProgressBarIndeterminateVisibility(false);
			ConnectionUtils.clearConnection(mContext, TAG);
		}

	};

	@Override
	public void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.reservation_view);
		timeSlot = (TimeSlot) getIntent().getSerializableExtra(
				TimeSlot.TIME_SLOT);

		startDate = (EditText) findViewById(R.id.start_date);
		startTime = (EditText) findViewById(R.id.start_time);
		endDate = (EditText) findViewById(R.id.end_date);
		endTime = (EditText) findViewById(R.id.end_time);
		btn = (Button) findViewById(R.id.btn_reserve);

		startDate.setText(TimeUtils.formatDate(timeSlot.getStartTime(),
				TimeUtils.DATE_FORMAT));
		startTime.setText(TimeUtils.formatDate(timeSlot.getStartTime(),
				TimeUtils.TIME_FORMAT));
		endDate.setText(TimeUtils.formatDate(timeSlot.getEndTime(),
				TimeUtils.DATE_FORMAT));
		endTime.setText(TimeUtils.formatDate(timeSlot.getEndTime(),
				TimeUtils.TIME_FORMAT));

//		startDate.addTextChangedListener(this);
//		endDate.addTextChangedListener(this);
//		startTime.addTextChangedListener(this);
//		endTime.addTextChangedListener(this);

	}

	/**
	 * check if the dates follows the rules must be called before firing service
	 * 
	 * @return
	 */
	private boolean checkDates() {
		String startTimeS = startDate.getText().toString() + "T"
				+ startTime.getText().toString();
		checkinDate = TimeUtils.getCalendarFromFormat(startTimeS,
				TimeUtils.IN_DATE_TIME_FORMAT);

		String endTimeS = endDate.getText().toString() + "T"
				+ endTime.getText().toString();
		checkoutDate = TimeUtils.getCalendarFromFormat(endTimeS,
				TimeUtils.IN_DATE_TIME_FORMAT);
		// System.out.println(checkoutDate.getTimeInMillis() -
		// checkinDate.getTimeInMillis());
		if (checkoutDate.getTimeInMillis() - checkinDate.getTimeInMillis() < 30 * 60000) {
			Toast.makeText(mContext, getString(R.string.min_duration),
					Toast.LENGTH_LONG).show();
			return false;
		}
		if(checkoutDate.before(Calendar.getInstance())){
			Toast.makeText(mContext, getString(R.string.old_reservation),
					Toast.LENGTH_LONG).show();
			
			return false;
		}
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(receiver, new IntentFilter(TAG));

		if (!ConnectionUtils.isConnecting(mContext, TAG))
		// it was connected
		{
			if (ConnectionUtils.wasConnected(mContext, TAG))
				// connection was successful
				if (ConnectionUtils.isResultSuccessful(mContext, TAG))
					receiver.onSuccess();
				else
					// it failed
					receiver.onFailure();
		} else { // there is an active connection
			setSupportProgressBarIndeterminateVisibility(true);
			disableView();
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(receiver);
		if (!ConnectionUtils.isConnecting(mContext, TAG)) {
			ConnectionUtils.clearConnection(mContext, TAG);
		}
	}

	public void showDatePicker(View v) {
		Calendar start = Calendar.getInstance();
		start.setTime(timeSlot.getStartTime());
		Calendar end = Calendar.getInstance();
		end.setTime(timeSlot.getEndTime());
		DialogFragment newFragment = DatePickerFragment.getInstance(
				v.getId(), start, end);
		newFragment.show(getSupportFragmentManager(),
				DatePickerFragment.DATE_PICKER_TAG);
	}

	public void showTimePicker(View v) {
		DialogFragment newFragment = TimePickerFragment
				.getInstance(v.getId());
		newFragment.show(getSupportFragmentManager(),
				TimePickerFragment.TIME_PICKER_TAG);
	}



	public void createNewReservation(View v) {
		if (!checkDates())
			return;
		// Check if no connection pop up a dialog
		if (!ConnectionUtils.isNetworkAvailable(mContext)) {
			// No connection
			ConnectionUtils.showNoConnectionDialog(mContext);
			return;
		} else { // Connection is available

			// Start loading dialog and connecting variables
			disableView();
			setSupportProgressBarIndeterminateVisibility(true);
			// start back-ground service to handle registration process
			Intent backgroud_regService = new Intent(this,
					ReservationService.class);
			backgroud_regService.setAction(TAG);
			backgroud_regService.putExtra(HTTPService.LOGIN_RQUIRED, true);
			backgroud_regService.putExtra(TimeSlot.TIME_SLOT, timeSlot);
			backgroud_regService.putExtra(Reservation.RESERVATION_SID,
					timeSlot.getId());
			// start Date
			backgroud_regService.putExtra(
					Reservation.RESERVATION_CHECK_IN_AT_1I,
					checkinDate.get(Calendar.YEAR));
			backgroud_regService.putExtra(
					Reservation.RESERVATION_CHECK_IN_AT_2I,
					checkinDate.get(Calendar.MONTH) + 1);
			backgroud_regService.putExtra(
					Reservation.RESERVATION_CHECK_IN_AT_3I,
					checkinDate.get(Calendar.DAY_OF_MONTH));
			backgroud_regService.putExtra(
					Reservation.RESERVATION_CHECK_IN_AT_4I,
					checkinDate.get(Calendar.HOUR_OF_DAY));
			backgroud_regService.putExtra(
					Reservation.RESERVATION_CHECK_IN_AT_5I,
					checkinDate.get(Calendar.MINUTE));
			// end Date
			backgroud_regService.putExtra(
					Reservation.RESERVATION_CHECK_OUT_AT_1I,
					checkoutDate.get(Calendar.YEAR));
			backgroud_regService.putExtra(
					Reservation.RESERVATION_CHECK_OUT_AT_2I,
					checkoutDate.get(Calendar.MONTH) + 1);
			backgroud_regService.putExtra(
					Reservation.RESERVATION_CHECK_OUT_AT_3I,
					checkoutDate.get(Calendar.DAY_OF_MONTH));
			backgroud_regService.putExtra(
					Reservation.RESERVATION_CHECK_OUT_AT_4I,
					checkoutDate.get(Calendar.HOUR_OF_DAY));
			backgroud_regService.putExtra(
					Reservation.RESERVATION_CHECK_OUT_AT_5I,
					checkoutDate.get(Calendar.MINUTE));
			startService(backgroud_regService);
		}

	}

	private void disableView() {
		startDate.setEnabled(false);
		endDate.setEnabled(false);
		startTime.setEnabled(false);
		endTime.setEnabled(false);
		btn.setEnabled(false);

	}

	private void enableView() {
		startDate.setEnabled(true);
		endDate.setEnabled(true);
		startTime.setEnabled(true);
		endTime.setEnabled(true);
		btn.setEnabled(true);
	}

	@Override
	public void onBackPressed() {
		if (ConnectionUtils.isConnecting(mContext, TAG)) {
			enableView();
			setSupportProgressBarIndeterminateVisibility(false);
			Intent loginCancel = new Intent(TAG + HTTPService.CANCEL);
			sendBroadcast(loginCancel);
			ConnectionUtils.clearConnection(mContext, TAG);
		} else
			super.onBackPressed();
	}
}
